package com.lifeverse.entity;

import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 生命体关系实体类
 * 记录生命体之间的各种关系
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "life_entity_relationships", indexes = {
    @Index(name = "idx_relationship_source", columnList = "source_entity_id"),
    @Index(name = "idx_relationship_target", columnList = "target_entity_id"),
    @Index(name = "idx_relationship_type", columnList = "relationship_type"),
    @Index(name = "idx_relationship_strength", columnList = "relationship_strength")
})
public class LifeEntityRelationship extends BaseEntity {
    
    /**
     * 关系类型枚举
     */
    public enum RelationshipType {
        COLLABORATION("协作关系", "两个生命体在某个项目或目标上进行协作"),
        COMPETITION("竞争关系", "两个生命体在某个领域存在竞争"),
        DEPENDENCY("依赖关系", "一个生命体依赖另一个生命体的资源或能力"),
        MENTORSHIP("指导关系", "一个生命体指导另一个生命体的成长"),
        FRIENDSHIP("友谊关系", "两个生命体之间的友好关系"),
        CONFLICT("冲突关系", "两个生命体之间存在冲突或对立"),
        PARENT_CHILD("父子关系", "一个生命体创造或孕育了另一个生命体"),
        SIBLING("兄弟关系", "两个生命体来自同一个父生命体"),
        FUSION("融合关系", "两个生命体正在或已经融合"),
        COMMUNICATION("通信关系", "两个生命体之间的信息交流关系"),
        SYMBIOSIS("共生关系", "两个生命体互相依赖，共同受益"),
        PARASITISM("寄生关系", "一个生命体从另一个生命体获益，但对方受损");
        
        private final String displayName;
        private final String description;
        
        RelationshipType(String displayName, String description) {
            this.displayName = displayName;
            this.description = description;
        }
        
        public String getDisplayName() {
            return displayName;
        }
        
        public String getDescription() {
            return description;
        }
    }
    
    /**
     * 关系状态枚举
     */
    public enum RelationshipStatus {
        ACTIVE("活跃", "关系正常活跃"),
        DORMANT("休眠", "关系暂时不活跃"),
        STRENGTHENING("加强中", "关系正在加强"),
        WEAKENING("减弱中", "关系正在减弱"),
        TERMINATED("已终止", "关系已经结束");
        
        private final String displayName;
        private final String description;
        
        RelationshipStatus(String displayName, String description) {
            this.displayName = displayName;
            this.description = description;
        }
        
        public String getDisplayName() {
            return displayName;
        }
        
        public String getDescription() {
            return description;
        }
    }
    
    /**
     * 源生命体
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "source_entity_id", nullable = false)
    private LifeEntity sourceEntity;
    
    /**
     * 目标生命体
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "target_entity_id", nullable = false)
    private LifeEntity targetEntity;
    
    /**
     * 关系类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "relationship_type", nullable = false, length = 20)
    private RelationshipType relationshipType;
    
    /**
     * 关系状态
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "relationship_status", nullable = false, length = 20)
    private RelationshipStatus relationshipStatus = RelationshipStatus.ACTIVE;
    
    /**
     * 关系强度（0-100）
     */
    @Column(name = "relationship_strength", nullable = false, precision = 5, scale = 2)
    private BigDecimal relationshipStrength;
    
    /**
     * 关系质量（0-100）
     */
    @Column(name = "relationship_quality", nullable = false, precision = 5, scale = 2)
    private BigDecimal relationshipQuality = BigDecimal.valueOf(50.00);
    
    /**
     * 信任度（0-100）
     */
    @Column(name = "trust_level", nullable = false, precision = 5, scale = 2)
    private BigDecimal trustLevel = BigDecimal.valueOf(50.00);
    
    /**
     * 互动频率（每天互动次数）
     */
    @Column(name = "interaction_frequency", nullable = false, precision = 7, scale = 2)
    private BigDecimal interactionFrequency = BigDecimal.valueOf(0.00);
    
    /**
     * 关系建立时间
     */
    @Column(name = "established_at", nullable = false)
    private LocalDateTime establishedAt;
    
    /**
     * 最后互动时间
     */
    @Column(name = "last_interaction_at")
    private LocalDateTime lastInteractionAt;
    
    /**
     * 关系结束时间
     */
    @Column(name = "terminated_at")
    private LocalDateTime terminatedAt;
    
    /**
     * 关系描述
     */
    @Column(name = "description", length = 500)
    private String description;
    
    /**
     * 关系标签（JSON格式存储）
     */
    @Column(name = "tags", length = 200)
    private String tags;
    
    /**
     * 关系属性（JSON格式存储）
     */
    @Column(name = "attributes", columnDefinition = "TEXT")
    private String attributes;
    
    /**
     * 互动统计数据（JSON格式存储）
     */
    @Column(name = "interaction_stats", columnDefinition = "TEXT")
    private String interactionStats;
    
    /**
     * 关系影响评分（-100到100）
     */
    @Column(name = "impact_score", nullable = false, precision = 6, scale = 2)
    private BigDecimal impactScore = BigDecimal.valueOf(0.00);
    
    /**
     * 是否为双向关系
     */
    @Column(name = "is_bidirectional", nullable = false)
    private Boolean isBidirectional = true;
    
    /**
     * 关系权重（用于网络分析）
     */
    @Column(name = "network_weight", nullable = false, precision = 5, scale = 4)
    private BigDecimal networkWeight = BigDecimal.valueOf(1.0000);
    
    @PrePersist
    protected void onCreate() {
        super.onCreate();
        if (establishedAt == null) {
            establishedAt = LocalDateTime.now();
        }
        if (lastInteractionAt == null) {
            lastInteractionAt = LocalDateTime.now();
        }
    }
    
    /**
     * 更新最后互动时间
     */
    public void updateLastInteractionTime() {
        this.lastInteractionAt = LocalDateTime.now();
    }
    
    /**
     * 加强关系
     */
    public void strengthenRelationship(BigDecimal amount) {
        this.relationshipStrength = this.relationshipStrength.add(amount);
        if (this.relationshipStrength.compareTo(BigDecimal.valueOf(100)) > 0) {
            this.relationshipStrength = BigDecimal.valueOf(100);
        }
        updateLastInteractionTime();
    }
    
    /**
     * 减弱关系
     */
    public void weakenRelationship(BigDecimal amount) {
        this.relationshipStrength = this.relationshipStrength.subtract(amount);
        if (this.relationshipStrength.compareTo(BigDecimal.ZERO) < 0) {
            this.relationshipStrength = BigDecimal.ZERO;
        }
        updateLastInteractionTime();
    }
    
    /**
     * 终止关系
     */
    public void terminateRelationship() {
        this.relationshipStatus = RelationshipStatus.TERMINATED;
        this.terminatedAt = LocalDateTime.now();
    }
    
    /**
     * 判断关系是否活跃
     */
    public boolean isActive() {
        return relationshipStatus == RelationshipStatus.ACTIVE;
    }
    
    /**
     * 判断关系是否强烈
     */
    public boolean isStrong() {
        return relationshipStrength.compareTo(BigDecimal.valueOf(70)) >= 0;
    }
    
    /**
     * 判断关系是否健康
     */
    public boolean isHealthy() {
        return relationshipQuality.compareTo(BigDecimal.valueOf(60)) >= 0 
               && trustLevel.compareTo(BigDecimal.valueOf(60)) >= 0;
    }
    
    /**
     * 获取关系持续时间（天数）
     */
    public long getDurationInDays() {
        LocalDateTime endTime = terminatedAt != null ? terminatedAt : LocalDateTime.now();
        return java.time.temporal.ChronoUnit.DAYS.between(establishedAt, endTime);
    }
    
    /**
     * 计算关系的综合评分
     */
    public BigDecimal calculateOverallScore() {
        return relationshipStrength
                .add(relationshipQuality)
                .add(trustLevel)
                .divide(BigDecimal.valueOf(3), 2, java.math.RoundingMode.HALF_UP);
    }
}